<template>
  <div v-html="renderedMarkdown" :class="customClass"></div>
</template>

<script>
import MarkdownIt from 'markdown-it';

export default {
  name: 'SgMarkdown',
  props: {
    content: {
      type: String,
      required: true
    },
    customClass: {
      type: String,
      default: ''
    }
  },
  computed: {
    renderedMarkdown() {
      return this.parseMarkdown(this.content);
    }
  },
  methods: {
    parseMarkdown(content) {
      // 创建 markdown-it 实例，启用 breaks 和表格支持
      const md = new MarkdownIt({
        breaks: true, // 将单个换行符转换为 <br>
        html: true,   // 允许 HTML 标签
        linkify: true, // 将类似 URL 的文本自动转换为链接
        typographer: true // 开启排版优化
      });

      // 处理换行符，将 \r\n 替换为 \n
      const normalizedContent = content.replace(/\r\n/g, '\n').replace(/\\n/g, '\n').replace(/\\r/g, '\n');

      // 渲染为 HTML
      return md.render(normalizedContent);
    }
  }
};
</script>

<style scoped>
/* 你可以根据需要自定义样式 */
.markdown-style {
  font-family: Arial, sans-serif;
  color: #333;
  line-height: 1.6;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin: 10px 0;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
}

pre {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}

code {
  background-color: #f5f5f5;
  padding: 2px 4px;
  border-radius: 4px;
}
</style>
